(function(angular) {
	'use strict';
	angular.module("fs.menu", [ 'menu/menuNav.html', 'menu/menuTemplate.html', 'menu/menuItemsTemplate.html' ]).
	directive('fsNav', [ '$timeout', function($timeout) {
		var controller = [ '$rootScope', '$scope', '$element', '$attrs', '$transclude', 'storageService','SYS_PARAMS', 
		  function($rootScope, $scope, $element, $attrs, $transclude, storageService, SYS_PARAMS) {
			var ctrl = this, watcher, watchers = [];
			ctrl.navigationCache = ctrl.navigationCache || {};
			$scope.$on('$destroy', function() {
				while (watchers.length) {
					(watchers.shift() || angular.noop)();
				}
			});
			watcher = $rootScope.$watch('pageId', function(pageId) {
				var menus, action, missActions, hasMenu, menuKeyPrefix;
				if (!pageId || (ctrl.currentStateUrl == pageId)) {
					return;
				}
				ctrl.currentStateUrl = pageId;
				menus = storageService.getMenuConfigInfo();
				if (ctrl.navigationCache[$rootScope.pageId]) {
					ctrl.navs = ctrl.navigationCache[$rootScope.pageId];
				} else {
					ctrl.navs = [];
					ctrl.currentStateUrl = ctrl.currentStateUrl.split(".");
					action = ctrl.currentStateUrl.pop();
					ctrl.currentStateUrl.push(action);
					action = action.toUpperCase();
					ctrl.currentStateUrl = ctrl.currentStateUrl.join('/');
					hasMenu = buildMenuNav(ctrl.currentStateUrl, menus, ctrl.navs);
					ctrl.currentStateUrl = ctrl.currentStateUrl.split('/');

					while (!hasMenu && ctrl.currentStateUrl.length > 2) {
						if (missActions) {
							missActions.unshift(ctrl.currentStateUrl.pop().toLowerCase());
						} else {
							ctrl.currentStateUrl.pop();
							missActions = [];
						}
						ctrl.currentStateUrl = ctrl.currentStateUrl.join('/');
						hasMenu = buildMenuNav(ctrl.currentStateUrl, menus, ctrl.navs);
						ctrl.currentStateUrl = ctrl.currentStateUrl.split('/');
					}

					if (!hasMenu && ctrl.currentStateUrl.length <= 2) {
						ctrl.currentStateUrl = ctrl.currentStateUrl.join('.');
						if ('waf.home' != ctrl.currentStateUrl) {
							ctrl.navs.unshift('title.navigation.' + ctrl.currentStateUrl.toLowerCase());
						}
					}
					if (missActions && missActions.length > 0) {
						angular.forEach(missActions, function(actionCode, index) {
							menuKeyPrefix = ctrl.navs.length > 0 ? ctrl.navs[0] : 'title.navigation.unkonw';
							ctrl.navs.unshift(menuKeyPrefix + '.' + actionCode);
						});
					}
					if (ctrl.navs.length > 0 && SYS_PARAMS.NAVIGATION_ACTIONS[action]) {
						ctrl.navs.unshift(SYS_PARAMS.NAVIGATION_ACTIONS[action]);
					}
					if (angular.isArray(ctrl.currentStateUrl)) {
						ctrl.currentStateUrl = ctrl.currentStateUrl.join('.');
					}
					ctrl.navigationCache[$rootScope.pageId] = ctrl.navs.reverse();
				}

			});
			watchers.push(watcher);

			function buildMenuNav(action, menuItems, navs) {
				var i = 0;
				for (i = 0; i < menuItems.length; i++) {
					if (menuItems[i].actionName && (menuItems[i].actionName + '/').indexOf(action+'/') >= 0) {
						navs.push(menuItems[i].displayName);
						return true;
					} else if (menuItems[i].subMenuItems) {
						if (buildMenuNav(ctrl.currentStateUrl, menuItems[i].subMenuItems, navs)) {
							navs.push(menuItems[i].displayName);
							return true;
						}
					}
				}
				return false;
			}
		}];
		return {
			restrict : 'EA',
			replace : true,
			controller : controller,
			controllerAs: 'fsNavController',
			link : function($scope, $element, $attr, ctrl, $transclude) {
			},
			templateUrl : function(element, attrs) {
			      return attrs.templateUrl || 'menu/menuNav.html';
		    }
		};
	}]).
	
	//<fs-menu ng-model="vm.menus"><fs-menu>
	directive('fsMenu', [ '$timeout', function($timeout) {
		var controller = [ '$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude) {
			
		} ];
		return {
			restrict : 'EA',
			replace : true,
			required : 'uibDropdown',
			controller : controller,
			link : function($scope, $element, $attrs, dropdownCtrl, $transclude) {
				var watcher;
				$scope.$on('$destroy', function() {
					watcher();
				});
				watcher = $scope.$watch($attrs.ngModel, function(newValue, oldValue){
					$scope.fsMenu = newValue;
					angular.forEach($scope.fsMenu, function(value, key) {
						$scope.fsMenu[key].icon = getIcon($scope.fsMenu[key]);
						$scope.fsMenu[key].state = value.actionName ? value.actionName.split('/').join('.') : value.actionName;
					});
				});
				$scope.isCurrent = function(items) {
					var i, f = false, currentStateName = ($scope.$state && $scope.$state.current) ? $scope.$state.current.name.split('_').join('.') : '';
					for (i = 0; i < items.length; i++) {
						if (currentStateName.indexOf(items[i].state) >= 0) {
							f =  true;
							break;
						} else if (items[i].subMenuItems) {
							f = $scope.isCurrent(items[i].subMenuItems);
						}
					}
					return f;
				};
			},
			templateUrl : function(element, attrs) {
			      return attrs.templateUrl || 'menu/menuTemplate.html';
		    }
		};
		
		function getIcon(menu) {
			var iconName;
			switch (menu.menuId) {
			case 'm1':
				iconName = 'workflow';
				break;
			case 'm2':
				iconName = 'admin';
				break;
			case 'm3':
				iconName = 'data';
				break;
			case 'm4':
				iconName = 'ldata';
				break;
			case 'm5':
				iconName = 'transaction';
				break;
			case 'm6':
				iconName = 'payerables';
				break;
			case 'm7':
				iconName = 'document';
				break;
			case 'm8':
				iconName = 'tools';
				break;
			case 'm9':
				iconName = 'limit';
				break;
			default:
				iconName = 'reports';

			}
			return iconName;
		}
	} ]).
	
	//<fs-menu-items ng-model="items"><fs-menu-items>
	directive('fsMenuItems', [ '$timeout', function($timeout) {
		var controller = [ '$rootScope', '$scope', '$element', '$attrs', '$transclude', function($rootScope, $scope, $element, $attrs, $transclude) {
			$scope.go = $rootScope.go;
		} ];
		return {
			restrict : 'EA',
			replace : true,
			required : '^^?uibDropdown',
			controller : controller,
			controllerAs : 'vm',
			scope : {
				fsMenu : '<ngModel',
				isOpen : '<'
			},
			link : function($scope, $element, $attr, dropdownCtrl, $transclude) {
				var watchers = [];
				$scope.$on('$destroy', function() {
					while (watchers.length) {
						(watchers.shift() || angular.noop)();
					}
				});
				angular.forEach($scope.fsMenu, function(value, key) {
					$scope.fsMenu[key].state = value.actionName ? value.actionName.split('/').join('.') : value.actionName;
				});
				$scope.open = function(item) {
					if (!$scope.isOpen) {
						item.open = false;
					}
					return item.open;
				};
				$scope.toggleDropdown = function($event, item) {
					if (!item.actionName) {
						item.open = !item.open;
						$event.preventDefault();
						$event.stopPropagation();
					} else {
						$scope.go(item.state, angular.fromJson(item.href));
					}
				};
			},
			templateUrl : function(element, attrs) {
			      return attrs.templateUrl || 'menu/menuItemsTemplate.html';
		    }
		};
	} ]);
	
	angular.module("menu/menuNav.html", []).run([ "$templateCache", function($templateCache) {
		$templateCache.put('menu/menuNav.html', ''
				+ '<div class="panel-heading fs-nav" ng-if="$state.current.name">'
				+ '    <ul class="list-inline">'
				+ '        <li><a href="#" ng-click="go(\'waf.home\')"><span>{{\'menu.home\'|translate}}</span></a>'
				+ '            <i ng-if="fsNavController.navs.length > 0" class="icon icon-arrow-right" style="margin-left:5px;"></i>'
				+ '        </li>'
				+ '        <li ng-repeat="navItem in fsNavController.navs">' 
				+ '            <span>{{navItem|translate}}</span><span ng-if="pageDescription && $index == (fsNavController.navs.length - 1)" style="font-size:16px">&nbsp;({{pageDescription | encode}})</span>' 
				+ '            <i ng-if="$index < (fsNavController.navs.length - 1)" class="icon icon-arrow-right" style="margin-left:5px;"></i>'
				+ '        </li>\n'
				+ '    </ul>'
				+ '</div>\n');
	} ]);
	angular.module("menu/menuTemplate.html", []).run([ "$templateCache", function($templateCache) {
		$templateCache.put('menu/menuTemplate.html', ''
				+ '<ul class="nav navbar-nav">'
				+ '    <li class="top-menu" ng-class="{\'current\':isCurrent(menu.subMenuItems), \'text-align: center;\':app.settings.collapseLeftMenu}" uib-dropdown role="menu" is-open="menu.isOpen" ng-repeat="menu in fsMenu track by $index">'
				+ '        <a href="#" data-toggle="dropdown" uib-dropdown-toggle>'
				+ '        	   <span ng-if="app.settings.leftMenu" class="icon icon-{{menu.icon}}" style="{{app.settings.collapseLeftMenu ? \'margin:13px 20px;\':\'\'}}"></span>'
				+ '            <span ng-if="!app.settings.leftMenu || !app.settings.collapseLeftMenu">{{menu.displayName|translate}}</span>'
				+ '            <span ng-if="!app.settings.leftMenu || (app.settings.leftMenu && !app.settings.collapseLeftMenu)" class="pull-right" ng-class="{\'dropup\': menu.isOpen}">'
				+ '                <span class="caret"></span>'
				+ '            </span>' 
				+ '        </a>\n'
				+ '        <div ng-if="app.settings.leftMenu" class="menu-border"></div>\n'
				+ '        <div fs-menu-items class="fs-menu-items" ng-model="menu.subMenuItems" is-open="menu.isOpen"></div>\n' 
				+ '    </li>\n'
				+ '    <li ng-if="app.settings.leftMenu" style="background-image:none">\n'
				+ '        <a href="#" ng-click="app.settings.collapseLeftMenu = !app.settings.collapseLeftMenu">'
				+ '            <span ng-class="{\'icon-colse-left\': !app.settings.collapseLeftMenu, \'icon-open-left\': app.settings.collapseLeftMenu}"></span>\n'
				+ '        </a>\n'
				+ '        <div class="menu-border"></div>\n'
				+ '    </li>\n'
				+ '</ul>\n');
	} ]);
	angular.module("menu/menuItemsTemplate.html", []).run([ "$templateCache", function($templateCache) {
		$templateCache.put('menu/menuItemsTemplate.html', ''
				+ '<ul class="animated fadeInUp" uib-dropdown-menu role="menu">'
				+ '    <li class="divider" ng-if="!!item.separator"></li>'
				+ '    <li role="menuItem" ng-repeat="item in fsMenu track by $index" ng-class="{\'dropdown-submenu\':!item.actionName, \'open\':open(item)}" ng-if="!item.separator">'
				+ '          <a href="#" ng-click="toggleDropdown($event, item)">'
				+ '              <span>{{item.displayName|translate}}</span>'
				+ '          </a>\n'
				+ '          <div fs-menu-items ng-if="item.subMenuItems" ng-model="item.subMenuItems" is-open="menu.isOpen"></div>\n'
				+ '    </li>\n' 
				+ '</ul>\n');
	} ]);
})(angular);
